package com.share.order.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;;
import com.share.common.core.constant.SecurityConstants;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.PageUtils;
import com.share.common.core.utils.StringUtils;
import com.share.common.security.utils.SecurityUtils;
import com.share.order.api.domain.SubmitOrderVo;
import com.share.order.domain.OrderBill;
import com.share.order.domain.OrderInfo;
import com.share.order.mapper.OrderBillMapper;
import com.share.order.mapper.OrderInfoMapper;
import com.share.order.service.OrderInfoService;
import com.share.rules.api.RemoteFeeRuleService;
import com.share.rules.api.domain.EndOrderVo;
import com.share.rules.api.domain.FeeRule;
import com.share.rules.api.domain.FeeRuleRequestForm;
import com.share.rules.api.domain.FeeRuleResponseVo;
import com.share.user.api.RemoteUserInfoService;
import com.share.user.api.domain.UserInfo;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.temporal.Temporal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderBillMapper orderBillMapper;
    @Autowired
    private RemoteFeeRuleService remoteFeeRuleService;
    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    /**
     *  获取未完成订单
     * @param userId
     * @return
     */
    @Override
    public OrderInfo getNoFinishedOrder(Long userId) {
        //根据用户id查询该用户是否有使用或未支付订单
        return orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .in(OrderInfo::getStatus, Arrays.asList("0", "1"))// 订单状态：0:充电中 1：未支付 2：已支付
                .orderByDesc(OrderInfo::getId)
                .last("limit 1")
        );
    }

    /**
     * 获取用户订单详情
     * @param id
     * @return
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = this.getById(id);
        //如果状态为充电中实时计算订单金额
        if ("0".equals(orderInfo.getStatus())) {
            // 实时计算订单时长
            int minutes = Minutes.minutesBetween(new DateTime(orderInfo.getStartTime()), new DateTime()).getMinutes();
            //如果订单时长大于0则实时计算订单金额
            if(minutes > 0){
                orderInfo.setDuration(minutes);
                //获取费用规则
                FeeRuleRequestForm feeRuleRequestForm = new FeeRuleRequestForm();
                //设置时长
                feeRuleRequestForm.setDuration(minutes);
                //设置费用规则id
                feeRuleRequestForm.setFeeRuleId(orderInfo.getFeeRuleId());
                //调用计费规则服务
                R<FeeRuleResponseVo> responseVoR = remoteFeeRuleService.calculateOrderFee(feeRuleRequestForm);
                if(R.FAIL==responseVoR.getCode()){
                    throw new RuntimeException(responseVoR.getMsg());
                }
                FeeRuleResponseVo feeRuleResponseVo = responseVoR.getData();
                // 设置订单金额
                orderInfo.setTotalAmount(feeRuleResponseVo.getTotalAmount());
                // 设置抵扣金额
                orderInfo.setDeductAmount(new BigDecimal(0));
                // 设置实际金额
                orderInfo.setRealAmount(feeRuleResponseVo.getTotalAmount());
            }else{
                orderInfo.setDuration(0);
                orderInfo.setTotalAmount(new BigDecimal(0));
                orderInfo.setDeductAmount(new BigDecimal(0));
                orderInfo.setRealAmount(new BigDecimal(0));
            }
        }
        //根据订单id查询订单明细
        List<OrderBill> orderBillList = orderBillMapper.selectList(new LambdaQueryWrapper<OrderBill>()
                .eq(OrderBill::getOrderId, id));
        //封装订单明细
        orderInfo.setOrderBillList(orderBillList);
        //查询用户信息
        R<UserInfo> userInfoResult = remoteUserInfoService.getUserInfo(orderInfo.getUserId());
        //判断用户信息是否为空
        if (StringUtils.isNull(userInfoResult) || StringUtils.isNull(userInfoResult.getData())) {
            throw new ServiceException("获取用户信息失败");
        }
        //判断用户信息是否成功
        if (R.FAIL == userInfoResult.getCode()) {
            throw new ServiceException(userInfoResult.getMsg());
        }
        //获取用户信息
        UserInfo userInfo = new UserInfo();
        //赋值给userInfo
        BeanUtils.copyProperties(userInfoResult.getData(), userInfo);
        orderInfo.setUserInfo(userInfo);
        return orderInfo;
    }

    /**
     * 提交订单
     * @param orderForm
     * @return
     */
    @Override
    public Long saveOrder(SubmitOrderVo orderForm) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(orderForm.getUserId());
        orderInfo.setOrderNo(RandomUtil.randomString(8));
        orderInfo.setPowerBankNo(orderForm.getPowerBankNo());
        orderInfo.setStartTime(new Date());
        orderInfo.setStartStationId(orderForm.getStartStationId());
        orderInfo.setStartStationName(orderForm.getStartStationName());
        orderInfo.setStartCabinetNo(orderForm.getStartCabinetNo());
        // 费用规则
        FeeRule feeRule = remoteFeeRuleService.getFeeRule(orderForm.getFeeRuleId()).getData();
        orderInfo.setFeeRuleId(orderForm.getFeeRuleId());
        orderInfo.setFeeRule(feeRule.getDescription());
        orderInfo.setStatus("0");
        orderInfo.setCreateTime(new Date());
        orderInfo.setCreateBy(SecurityUtils.getUsername());
        //用户昵称
        UserInfo userInfo = remoteUserInfoService.getUserInfo(orderInfo.getUserId()).getData();

        orderInfo.setNickname(userInfo.getNickname());
        orderInfoMapper.insert(orderInfo);
        return orderInfo.getId();
    }




    /**
     * 结束订单
     * @param endOrderVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void endOrder(EndOrderVo endOrderVo) {
        // 获取充电中的订单，如果存在，则结束订单； 如果不存在，则返回（初始化插入，无订单）
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getPowerBankNo, endOrderVo.getPowerBankNo())
                .eq(OrderInfo::getStatus, "0") //订单状态：0:充电中
                .orderByDesc(OrderInfo::getCreateTime)
                .last("limit 1")
        );
        if (orderInfo == null) {
            return;
        }

        orderInfo.setEndTime(endOrderVo.getEndTime());
        orderInfo.setEndStationId(endOrderVo.getEndStationId());
        orderInfo.setEndStationName(endOrderVo.getEndStationName());
        orderInfo.setEndCabinetNo(endOrderVo.getEndCabinetNo());
        int duration = Minutes.minutesBetween(new DateTime(orderInfo.getStartTime()), new DateTime(orderInfo.getEndTime())).getMinutes();
        orderInfo.setDuration(duration);

        // 费用计算
        FeeRuleRequestForm feeRuleRequestForm = new FeeRuleRequestForm();
        feeRuleRequestForm.setDuration(duration);
        feeRuleRequestForm.setFeeRuleId(orderInfo.getFeeRuleId());
        R<FeeRuleResponseVo> feeRuleResponseVoResult = remoteFeeRuleService.calculateOrderFee(feeRuleRequestForm);
        if (R.FAIL == feeRuleResponseVoResult.getCode()) {
            throw new ServiceException(feeRuleResponseVoResult.getMsg());
        }
        FeeRuleResponseVo feeRuleResponseVo = feeRuleResponseVoResult.getData();

        // 设置订单金额
        orderInfo.setTotalAmount(feeRuleResponseVo.getTotalAmount());
        orderInfo.setDeductAmount(new BigDecimal(0));
        orderInfo.setRealAmount(feeRuleResponseVo.getTotalAmount());
        if(orderInfo.getRealAmount().subtract(new BigDecimal(0)).doubleValue() == 0) {
            orderInfo.setStatus("2");
        } else {
            orderInfo.setStatus("1");
        }
        orderInfoMapper.updateById(orderInfo);

        // 插入免费订单账单
        OrderBill freeOrderBill = new OrderBill();
        freeOrderBill.setOrderId(orderInfo.getId());
        freeOrderBill.setBillItem(feeRuleResponseVo.getFreeDescription());
        freeOrderBill.setBillAmount(new BigDecimal(0));
        orderBillMapper.insert(freeOrderBill);

        // 插入超出免费订单账单
        if (feeRuleResponseVo.getExceedPrice().doubleValue() > 0) {
            OrderBill exceedOrderBill = new OrderBill();
            exceedOrderBill.setOrderId(orderInfo.getId());
            exceedOrderBill.setBillItem(feeRuleResponseVo.getExceedDescription());
            exceedOrderBill.setBillAmount(feeRuleResponseVo.getExceedPrice());
            orderBillMapper.insert(exceedOrderBill);
        }
    }

    /**
     * 获取用户订单信息
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<OrderInfo> userOrderInfo(Long userId, Integer pageNum, Integer pageSize) {
        // 获取用户订单
        List<OrderInfo> list = this.list(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .orderByDesc(OrderInfo::getCreateTime));
        // 判断是否为空
        if(list.size() > 0){
            // 判断订单状态
            for (OrderInfo orderInfo : list) {
                //如果订单状态为充电中，则实时计算订单金额
                if (orderInfo.getStatus().equals("0")) {
                    // 获取订单时长
                    int duration = Minutes.minutesBetween(new DateTime(orderInfo.getStartTime()), new DateTime()).getMinutes();
                    // 如果订单时长大于0，则更新订单时长
                    if(duration > 0){
                        orderInfo.setDuration(duration);
                        // 费用计算
                        FeeRuleRequestForm feeRuleRequestForm = new FeeRuleRequestForm();
                        // 订单时长
                        feeRuleRequestForm.setDuration(duration);
                        // 费用规则id
                        feeRuleRequestForm.setFeeRuleId(orderInfo.getFeeRuleId());
                        // 获取费用规则
                        R<FeeRuleResponseVo> feeRuleResponseVoResult = remoteFeeRuleService.calculateOrderFee(feeRuleRequestForm);
                        // 判断费用规则
                        if (R.FAIL == feeRuleResponseVoResult.getCode()) {
                            throw new ServiceException(feeRuleResponseVoResult.getMsg());
                        }
                        // 设置订单金额
                        FeeRuleResponseVo feeRuleResponseVo = feeRuleResponseVoResult.getData();
                        orderInfo.setTotalAmount(feeRuleResponseVo.getTotalAmount());
                        orderInfo.setDeductAmount(new BigDecimal(0));
                        orderInfo.setRealAmount(feeRuleResponseVo.getTotalAmount());
                    }else{
                        orderInfo.setDuration(0);
                        orderInfo.setTotalAmount(new BigDecimal(0));
                        orderInfo.setDeductAmount(new BigDecimal(0));
                        orderInfo.setRealAmount(new BigDecimal(0));
                    }
                }
            }
        }
        return list;
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        return orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getOrderNo, orderNo));
    }

    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getStatus));
        //未支付
        if ("1".equals(orderInfo.getStatus())) {
            orderInfo.setStatus("2");
            orderInfo.setPayTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}
